import numpy as np
import datetime


def mae(x, y, axis=None):
    assert x.shape == y.shape

    diff = np.absolute(x - y)
    mae = np.mean(diff, axis=axis)
    return mae

def mse(x,y):
    assert x.shape == y.shape

    diff = np.square(x - y)
    mse = np.mean(diff)
    return mse

ths = [0.1,10,25,50,100]
def ts(x, y):
    assert x.shape == y.shape

    ts = []
    for th in ths:
        a = np.sum((x >= th) & (y >= th))
        b = np.sum((x >= th) & (y < th))
        c = np.sum((x < th) & (y >= th))
        d = np.sum((x < th) & (y < th))

        all = a + b + c + d
        assert (x.size == all)

        _ts = a / (a + b + c)
        ts.append(_ts)

    return ts


def acc_2(sc, stadict, wes, nor, issued):
    keys = stadict.keys()
    sh = sc.shape
    scr = np.zeros((sh[0]))
    for i in range(sh[0]):      #pred
        time = issued + datetime.timedelta(days=i+1)
        key = time.strftime('%Y%m%d%H')
        xs = sc[i]
        if not key in keys:
            scr[i] = np.nan
            continue
        xm = stadict[key]
        num = xm.shape[0]
        xsc_cnt = 0
        for n in range(num):
            t = xm[n][4].astype(np.float)
            lat = xm[n][2].astype(np.float)
            lon = xm[n][1].astype(np.float)
            px = int(round((lon - wes) / 0.05))
            py = 223 - int(round((nor - lat) / 0.05))
            xsc_err = abs(xs[py][px] - t)
            if xsc_err < 2.0:
                xsc_cnt += 1

        scr[i] = xsc_cnt * 100.0 / 109.0
    return scr